package day53_416;

import java.util.Arrays;

/**
 * @ClassName Solution
 * @Description DP解法
 * @Author clockTown
 * @Date 2021/7/1 20:36
 * @Version 1.0
 */
public class Solution1 {
    public boolean canPartition(int[] nums) {
        int n = nums.length;
        if (n < 2) {
            return false;
        }
        int sum = 0, maxNum = 0;
        for (int num : nums) {
            maxNum = Math.max(maxNum, num);
            sum += num;
        }
        if (sum % 2 == 1) {
            return false;
        }

        int target = sum / 2;
        if (maxNum > target) {
            return false;
        }

        boolean[][] dp = new boolean[n][target + 1];
        //如果不取任何数, 则整数和为0
        for (int i = 0; i < n; i++) {
            dp[i][0] = true;
        }
        //如果只取第一个数, 则整数和为 nums[0]
        dp[0][nums[0]] = true;

        for (int i = 1; i < n; i++) {
            int num = nums[i];
            for (int j = 0; j <= target; j++) {
                if (j >= num) {
                    dp[i][j] = dp[i - 1][j] || dp[i - 1][j - num];
                } else {
                    dp[i][j] = dp[i - 1][j];
                }
            }
        }
        return dp[n - 1][target];
    }
}
